package com.jiawa.train.business.controller;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.jiawa.train.business.req.ConfirmOrderDoReq;
import com.jiawa.train.business.service.IConfirmOrderService;
import com.jiawa.train.business.service.impl.BeforeConfirmOrderService;
import com.jiawa.train.common.exception.BusinessExceptionEnum;
import com.jiawa.train.common.resp.CommonResp;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 确认订单 前端控制器
 * </p>
 *
 * @author hrz
 * @since 2025-09-08
 */
@RestController
@RequestMapping("/confirm-order")
@RequiredArgsConstructor
@Slf4j
public class ConfirmOrderController {

    @Value("${spring.profiles.active}")
    private String env;

    private final StringRedisTemplate redisTemplate;
    private final BeforeConfirmOrderService beforeConfirmOrderService;
    private final IConfirmOrderService confirmOrderService;


    @PostMapping("/do")
    @SentinelResource(value = "confirmOrderDo",blockHandler = "doConfirmBlock")
    public CommonResp<Object> doConfirm(@Validated @RequestBody ConfirmOrderDoReq req) {
        //1.校验验证码 - 开发时不进行验证码校验
        if(!("dev".equals(env))){
            String imageCodeToken = req.getImageCodeToken();
            System.out.println(imageCodeToken);
            String redisCode = redisTemplate.opsForValue().get(imageCodeToken);
            System.out.println(redisCode);
            if(ObjectUtil.isNull(redisCode)){
                log.info("验证码校验失败,redisCode为空");
                return new CommonResp<>(false,"验证码已过期",null);
            }
            if(req.getImageCode().equalsIgnoreCase(redisCode)){
                log.info("验证码校验成功");
                //移除缓存中的验证码
                redisTemplate.delete(imageCodeToken);
            }else{
                log.info("验证码校验失败");
                return new CommonResp<>(false,"验证码错误",null);
            }
        }
        Long id = beforeConfirmOrderService.beforeDoConfirm(req);
        return new CommonResp<>(String.valueOf(id));
    }

    @GetMapping("/query-line-count/{id}")
    public CommonResp<Integer> queryLineCount(@PathVariable Long id) {
        Integer count = confirmOrderService.queryLineCount(id);
        return new CommonResp<>(count);
    }

    private CommonResp<Object> doConfirmBlock(ConfirmOrderDoReq req, BlockException e) {
        log.info("doConfirmBlock, req={}", req);
        CommonResp<Object> r = new CommonResp<>();
        r.setMessage("确认订单限流");
        r.setSuccess(true);
        r.setContent(BusinessExceptionEnum.CONFIRM_ORDER_FLOW_EXCEPTION.getDesc());
        return r;
    }
}
